<?php
namespace app\api\controller\vuser;
class Userbill extends Base
{
  	public function __construct() {
  		parent::__construct();
  		$this->checkLogin();
  	}

  	//交易记录
  	public function lists() {
    		$d = $this->post();
    		$rule = [
    			'type' => 'require|integer',
    		];
    		$msg = [
    		];
    		check($rule, $msg, $d);

    		$map = [];
    		$map[] = ["and", "user_id", "=", $this->userinfo["id"]];
        if($d['type']){
          $map[] = $d['type']==1?["and", "type", "<", 200]:["and", "type", ">", 199];
        }
    		if (!$d['ym']) {
    			$w1 = where($map);
    			$result  = $this->db->query("select create_time from user_bill $w1[0] order by id desc limit 1", $w1[1], 1);
          $d['ym'] = $result ? date("Y-m", $result['create_time']) : date("Y-m", time());
    		}
    		//找出月分
    		$month = [$d['ym']];
    		for ($i = 1; $i < $d['limit']; $i++) {
    			$month[] = date("Y-m", strtotime("-{$i} month", strtotime($d['ym'])));
    		}
    		$start_time = month_time(end($month))['start_time'];
    		$end_time = month_time($month[0])['end_time'];
    		$map[] = ["and", "create_time", ">=", $start_time];
    		$map[] = ["and", "create_time", "<=", $end_time];

    		$w = where($map);
    		$rs = $this->db->query("select * from user_bill $w[0] order by id desc ", $w[1]);

    		$month_temp = [];
    		foreach ($month as $v) {
    			$month_temp[$v] = [];
    		}
    		foreach ($rs as $k => $v) {
    			$ym = date('Y-m', $v['create_time']);
    			if (!isset($month_temp[$ym]['list'])) {
    				$month_temp[$ym]['list'] = [];
    				$month_temp[$ym]['total'] = 0;
    				$month_temp[$ym]['year'] = $ym;
    			}
          $v['create_time_name'] = com_time_format($v['create_time'],'Y-m-d');
    			$v['type_name'] = c("type.user_bill_type.{$v['type']}");
    			$month_temp[$ym]['list'][] = $v;
          $month_temp[$ym]['total'] += $v['money'];
    		}
    		$temp = [
    			'month_data' => array_filter(array_values($month_temp)),
    			'next_month' => date("Y-m", strtotime("-1 month", $end_time)),
    		];
    		suc($temp);
  	}
}
